<?php
namespace control;
/*
*生产用料差异类
*/

class productDiffClass extends adIndexClass
{
    private const page = 'productDiff';
    private const title = '生产用料差异';
    private const table = 'machining_order';
    private const tableMx = 'machining_order_detail';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "单据日期",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'quantity'          => [
                        'name'  => '预计用量',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'pickNum'          => [
                        'name'  => '领料数量',
                        'width' => 120,
                    ],
                    'refundNum'          => [
                        'name'  => '退料数量',
                        'width' => 120,
                    ],
                    'disNum'          => [
                        'name'  => '配料数量',
                        'width' => 120,
                    ],
                    'actual'          => [
                        'name'  => '实际用量',
                        'width' => 120,
                    ],
                    'excess'          => [
                        'name'  => '超量',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                ],
                [
                    "单据日期"   => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认'
        );
        $and ='';
        if ($this->post('createTime')) {
            //单据日期
            $and .=self::timeComparison($this->post('createTime'),field: 'b.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.recordDate desc,b.orderNo desc,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,b.orderNo,b.recordDate,b.lineId,b.type,c.code,c.name as materialName,c.model",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //领料
            $pickNum=0;
            $pickOrderAll = find(array(
                'table'=>'pick_order as a join pick_order_detail as b on a.id = b.orderId',
                'field'=>'b.id',
                "where"=>"a.state = '已确认' and a.type=0 and b.sourceId = '$array[id]' and b.materialId = '$array[materialId]'"
            ));
            foreach ($pickOrderAll['array'] as $val){
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]' and num >0 and coid = '" . self::$coid . "'"));
                foreach ($inventoryAll['array'] as $item) {
                    $pickNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                }
            }
            $pickNum = self::formattingFigure($pickNum,'numPrecision');
            //退料
            $refundNum=0;
            $refundOrderAll = find(array(
                'table'=>'pick_order as a join pick_order_detail as b on a.id = b.orderId',
                'field'=>'b.id',
                "where"=>"a.state = '已确认' and a.type=1 and b.sourceId = '$array[id]' and b.materialId = '$array[materialId]'"
            ));
            foreach ($refundOrderAll['array'] as $val){
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]' and num >0 and coid = '" . self::$coid . "'"));
                foreach ($inventoryAll['array'] as $item) {
                    $refundNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                }
            }
            $refundOrderAll = find(array(
                'table'=>'pick_order as a join pick_order_detail as b on a.id = b.orderId',
                'field'=>'b.id,b.unit,b.num',
                "where"=>"a.state = '已确认' and a.type=1 and b.sourceId in (select id from pick_order_detail where sourceId = '$array[id]') and b.materialId = '$array[materialId]'"
            ));
            foreach ($refundOrderAll['array'] as $val){
                $refundNum+=machiningOrderClass::material_num_change($array['materialId'],$val['unit'],$array['unit'],$val['num']);
            }
            $refundNum = self::formattingFigure($refundNum,'numPrecision');

            //配料
            $disNum=0;
            $all = find(array(
                'table'=>'material_distribute_num as a join material_distribute as b on a.orderId = b.id',
                'field'=>"a.*",
                'where'=>"b.state = '已确认' and a.materialId = '$array[materialId]' and machiningOrderMxId = '$array[targetSkuId]'"
            ));
            foreach ($all['array'] as $val){
                $disNum+=machiningOrderClass::material_num_change($array['materialId'],$val['unit'],$array['unit'],$val['num']);
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'quantity':
                        $row[] = self::lostZero($array['quantity'],'numPrecision');
                        break;
                    case 'pickNum':
                        $row[] = self::lostZero($pickNum,'numPrecision');
                        break;
                    case 'refundNum':
                        $row[] = self::lostZero($refundNum,'numPrecision');
                        break;
                    case 'disNum':
                        $row[] = self::lostZero($disNum,'numPrecision');
                        break;
                    case 'actual':
                        $row[] = $pickNum+$disNum-$refundNum;
                        break;
                    case 'excess':
                        $row[] = self::formattingFigure(machiningOrderClass::notLessThanZero($pickNum+$disNum-$refundNum-$array['quantity']),'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.quantity),0) as quantity",
        ]);
        // 根据生产计划领退料的数据
        $inventory = find(array(
            'table'  => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on c.id = a.materialId join pick_order_detail as pod on pod.sourceId = a.id join inventory_detail as mx on mx.sourceId = pod.id join pick_order as po on po.id = pod.orderId ",
            'single'=>$where." and po.state = '已确认' and mx.num >0  ",
            'field'=>"SUM(if(po.type=0,(CASE WHEN mx.unit = c.unit_one THEN mx.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.num*c.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END),0)) AS pick,
            SUM(if(po.type=0,0,(CASE WHEN mx.unit = c.unit_one THEN mx.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.num*c.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END))) AS refund"
        ));
        // 根据领料单退料的数量
        $pickRefund = find(array(
            'table'  => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on c.id = a.materialId join pick_order_detail as pod on pod.sourceId = a.id join pick_order_detail as mx on mx.sourceId = pod.id join pick_order as po on po.id = mx.orderId ",
            'single'=>$where." and po.state = '已确认' and po.type =1  ",
            'field'=>"SUM((CASE WHEN mx.unit = c.unit_one THEN mx.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.num*c.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)) AS refund"
        ));
        // 配料
        $dis = find(array(
            'table'  => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on c.id = a.materialId join material_distribute_num as mdn on mdn.machiningOrderMxId = a.targetSkuId join material_distribute as md on md.id = mdn.orderId ",
            'single'=>$where." and md.state = '已确认' ",
            'field'=>"SUM((CASE WHEN mdn.unit = c.unit_one THEN mdn.num*c.unit_one_num WHEN mdn.unit = c.unit_two THEN mdn.num*c.unit_two_num ELSE mdn.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)) AS num"
        ));
        $total    = [
            'quantity'        => self::lostZero($totalQuery['quantity'], 'numPrecision'),
            'pickNum'        => self::lostZero($inventory['pick'], 'numPrecision'),
            'refundNum'        => self::formattingFigure($inventory['refund']+$pickRefund['refund'], 'numPrecision'),
            'disNum'        => self::lostZero($dis['num'], 'numPrecision'),
            'actual'        => self::formattingFigure($inventory['pick']+$dis['num']-($inventory['refund']+$pickRefund['refund']), 'numPrecision'),
            'excess'        => self::formattingFigure(machiningOrderClass::notLessThanZero($inventory['pick']+$dis['num']-($inventory['refund']+$pickRefund['refund'])-$totalQuery['quantity']), 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on c.id = a.materialId",
                    'field'=>"a.*,b.orderNo,b.recordDate,b.lineId,b.type,c.code,c.name as materialName,c.model",
                    "where" => "id in ('".implode("','", $checkedId)."') order by b.recordDate desc,b.orderNo desc,a.list",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array) {
                $column = [];
                //领料
                $pickNum      = 0;
                $pickOrderAll = find(array(
                    'table' => 'pick_order as a join pick_order_detail as b on a.id = b.orderId',
                    "where" => "a.state = '已确认' and a.type=0 and b.sourceId = '$array[id]' and b.materialId = '$array[materialId]'"
                ));
                foreach ($pickOrderAll['array'] as $val) {
                    $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]' and num >0 and coid = '" . self::$coid . "'"));
                    foreach ($inventoryAll['array'] as $item) {
                        $pickNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                    }
                }
                $pickNum = self::formattingFigure($pickNum, 'numPrecision');
                //退料
                $refundNum      = 0;
                $refundOrderAll = find(array(
                    'table' => 'pick_order as a join pick_order_detail as b on a.id = b.orderId',
                    "where" => "a.state = '已确认' and a.type=1 and b.sourceId = '$array[id]' and b.materialId = '$array[materialId]'"
                ));
                foreach ($refundOrderAll['array'] as $val) {
                    $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]' and num >0 and coid = '" . self::$coid . "'"));
                    foreach ($inventoryAll['array'] as $item) {
                        $refundNum += machiningOrderClass::material_num_change($array['materialId'], $item['unit'], $array['unit'], $item['num']);
                    }
                }
                $refundOrderAll = find(array(
                    'table' => 'pick_order as a join pick_order_detail as b on a.id = b.orderId',
                    "where" => "a.state = '已确认' and a.type=1 and b.sourceId in (select id from pick_order_detail where sourceId = '$array[id]') and b.materialId = '$array[materialId]'"
                ));
                foreach ($refundOrderAll['array'] as $val) {
                    $refundNum += machiningOrderClass::material_num_change($array['materialId'], $val['unit'], $array['unit'], $val['num']);
                }
                $refundNum = self::formattingFigure($refundNum, 'numPrecision');

                //配料
                $disNum = 0;
                $all    = find(array(
                    'table' => 'material_distribute_num as a join material_distribute as b on a.orderId = b.id',
                    'field' => "a.*",
                    'where' => "b.state = '已确认' and a.materialId = '$array[materialId]' and machiningOrderMxId = '$array[targetSkuId]'"
                ));
                foreach ($all['array'] as $val) {
                    $disNum += machiningOrderClass::material_num_change($array['materialId'], $val['unit'], $array['unit'], $val['num']);
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '预计用量'=>self::lostZero($array['quantity'],'numPrecision'),
                            '领料数量'=>$pickNum,
                            '退料数量'=>$refundNum,
                            '配料数量'=>$disNum,
                            '实际用量'=>$pickNum+$disNum-$refundNum,
                            '超量'=>self::formattingFigure(machiningOrderClass::notLessThanZero($pickNum+$disNum-$refundNum-$array['quantity']),'numPrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了生产用料差异";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "生产用料差异.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'预计用量',
                    'aliasName'=>'预计用量',
                ],
                [
                    'columnName'=>'领料数量',
                    'aliasName'=>'领料数量',
                ],
                [
                    'columnName'=>'退料数量',
                    'aliasName'=>'退料数量',
                ],
                [
                    'columnName'=>'配料数量',
                    'aliasName'=>'配料数量',
                ],
                [
                    'columnName'=>'实际用量',
                    'aliasName'=>'实际用量',
                ],
                [
                    'columnName'=>'超量',
                    'aliasName'=>'超量',
                ],
            ]
        };
    }
}

